// API接口封装

const API_BASE = '/api';

// 通用请求函数
async function request(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API请求失败:', error);
        showMessage(`请求失败: ${error.message}`, 'error');
        throw error;
    }
}

// 工作进度计划API
const workPlanAPI = {
    // 获取所有工作进度
    async getAll() {
        return request(`${API_BASE}/work-plan`);
    },
    
    // 创建工作进度
    async create(data) {
        return request(`${API_BASE}/work-plan`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新工作进度
    async update(id, data) {
        return request(`${API_BASE}/work-plan/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除工作进度
    async delete(id) {
        return request(`${API_BASE}/work-plan/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索工作进度
    async search(query) {
        return request(`${API_BASE}/work-plan/search?q=${encodeURIComponent(query)}`);
    }
};

// 外发清单API
const outsourceAPI = {
    // 获取所有外发清单
    async getAll() {
        return request(`${API_BASE}/outsource`);
    },
    
    // 创建外发清单
    async create(data) {
        return request(`${API_BASE}/outsource`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新外发清单
    async update(id, data) {
        return request(`${API_BASE}/outsource/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除外发清单
    async delete(id) {
        return request(`${API_BASE}/outsource/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索外发清单
    async search(query) {
        return request(`${API_BASE}/outsource/search?q=${encodeURIComponent(query)}`);
    }
};

// 数据查询API
const dataQueryAPI = {
    // 获取所有数据
    async getAll() {
        return request(`${API_BASE}/data-query`);
    },
    
    // 创建数据记录
    async create(data) {
        return request(`${API_BASE}/data-query`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新数据记录
    async update(id, data) {
        return request(`${API_BASE}/data-query/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除数据记录
    async delete(id) {
        return request(`${API_BASE}/data-query/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索数据
    async search(query) {
        return request(`${API_BASE}/data-query/search?q=${encodeURIComponent(query)}`);
    },
    
    // 更新状态
    async updateStatus(id, statusType, status) {
        return request(`${API_BASE}/data-query/${id}/status`, {
            method: 'PUT',
            body: JSON.stringify({ statusType, status })
        });
    }
};

// 钢网追踪API
const steelMeshAPI = {
    // 获取所有钢网记录
    async getAll() {
        return request(`${API_BASE}/steel-mesh`);
    },
    
    // 创建钢网记录
    async create(data) {
        return request(`${API_BASE}/steel-mesh`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新钢网记录
    async update(id, data) {
        return request(`${API_BASE}/steel-mesh/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除钢网记录
    async delete(id) {
        return request(`${API_BASE}/steel-mesh/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索钢网记录
    async search(query) {
        return request(`${API_BASE}/steel-mesh/search?q=${encodeURIComponent(query)}`);
    }
};

// 治具追踪API
const fixtureAPI = {
    // 获取所有治具记录
    async getAll() {
        return request(`${API_BASE}/fixture`);
    },
    
    // 创建治具记录
    async create(data) {
        return request(`${API_BASE}/fixture`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新治具记录
    async update(id, data) {
        return request(`${API_BASE}/fixture/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除治具记录
    async delete(id) {
        return request(`${API_BASE}/fixture/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索治具记录
    async search(query) {
        return request(`${API_BASE}/fixture/search?q=${encodeURIComponent(query)}`);
    }
};

// SOP签核追踪API
const sopAPI = {
    // 获取所有SOP记录
    async getAll() {
        return request(`${API_BASE}/sop`);
    },
    
    // 创建SOP记录
    async create(data) {
        return request(`${API_BASE}/sop`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 更新SOP记录
    async update(id, data) {
        return request(`${API_BASE}/sop/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },
    
    // 删除SOP记录
    async delete(id) {
        return request(`${API_BASE}/sop/${id}`, {
            method: 'DELETE'
        });
    },
    
    // 搜索SOP记录
    async search(query) {
        return request(`${API_BASE}/sop/search?q=${encodeURIComponent(query)}`);
    }
};

// 导入导出API
const importExportAPI = {
    // 导出数据
    async exportData(type, format) {
        return request(`${API_BASE}/export/${type}/${format}`);
    },
    
    // 导入数据
    async importData(type, data) {
        return request(`${API_BASE}/import/${type}`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },
    
    // 获取延期项目
    async getOverdueItems() {
        return request(`${API_BASE}/overdue`);
    }
};

// 检查延期项目
async function checkOverdueItems() {
    try {
        const overdueItems = await importExportAPI.getOverdueItems();
        if (overdueItems.length > 0) {
            const content = `
                <div class="overflow-x-auto">
                    <table class="table table-zebra">
                        <thead>
                            <tr>
                                <th>类型</th>
                                <th>工单号</th>
                                <th>机型</th>
                                <th>延期日期</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${overdueItems.map(item => `
                                <tr>
                                    <td>${item.type}</td>
                                    <td>${item.workOrder || '-'}</td>
                                    <td>${item.model || '-'}</td>
                                    <td>${formatDate(item.dueDate)}</td>
                                    <td>${item.remark || '-'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            showModal('延期工单提醒', content);
        } else {
            showMessage('暂无延期工单', 'success');
        }
    } catch (error) {
        showMessage('检查延期工单失败', 'error');
    }
}
